﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Quartz.Util;
using Spider.Mode;

namespace Spider.Service
{
    public class StockCheckerService
    {
        private static readonly string url = @"https://api.guosen.com.cn:1443/tcapp/market-data/stock-list-foshanquant.do";
        
        private static readonly Dictionary<string, string> Map = new Dictionary<string, string>();

        private static DateTime _dateTime;

        public static bool IsStock(string text)
        {
            if (DateTime.Today != _dateTime)
            {
                InitData();
            }

            return Map.ContainsKey(text);
        }
        
        public static bool ContainStock(string text)
        {
            if (DateTime.Today != _dateTime)
            {
                InitData();
            }
            char[] sp = { '：' };
            var strings = text.Split(sp, StringSplitOptions.RemoveEmptyEntries);
            if (strings.Length == 2)
            {
                return Map.Keys.Any(strings[0].Equals);
            }

            return Map.Keys.Any(text.Contains);
        }

        public static string GetStockCode(string stockName)
        {
            if (DateTime.Today != _dateTime)
            {
                InitData();
            }

            return Map.TryGetAndReturn(stockName);
        }

        public static void InitData()
        {
            _dateTime = DateTime.Today;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Get;
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string retString = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();

            StockCheck stockCheck = JsonConvert.DeserializeObject<StockCheck>(retString);
            stockCheck?.Stocks.ForEach(m =>
            {
                m.name = m.name.Replace(" ", "");
                if (!Map.ContainsKey(m.name))
                {
                    Map.Add(m.name,m.code);
                }
                else
                {
                    Map.Remove(m.name);
                    Map.Add(m.name, m.code);
                }
            });
        }
        
    }
}